import Dexie, { Table } from "dexie";
import { LogMessage, ChatRoom, BaseInfo, LogAll } from "../../serve/interfaces";

export class SourceDB extends Dexie {
  log: Table<LogMessage & BaseInfo>;
  chatroom: Table<ChatRoom & BaseInfo, ChatRoomId>;
  chatroom_last_message: Table<ChatroomLastMessage, ChatRoomId>;
  seen_count: Table<SeenCount, ChatRoomId>;
  constructor(currentUsername?: string) {
    super(`CSZG_CHAT_STORE${currentUsername ? "-" + currentUsername : ""}`);
    this.version(2).stores({
      log: "_id,created_by,modified_by,gmt_created,gmt_modified,type,message,to, chatroom_id",
      chatroom: "_id,created_by,modified_by,gmt_created,gmt_modified,name,desc,notice,is_muted,users",
      chatroom_last_message: "chatroom_id, gmt_modified, message.gmt_modified",
      seen_count: "chatroom_id, seen_count",
    });
  }
}

export default new SourceDB();

type ChatRoomId = BaseInfo["_id"];

interface MergeCategoryMessage {
  chatroom_id: ChatRoomId;
  messages: LogMessage[];
}

interface SeenCount {
  chatroom_id: ChatRoomId;
  seen_count?: number;
}

export type MessageRelated = Omit<LogAll, "connect" | "server_error">;

// type ChatroomLastMessage = MessageRelated[keyof MessageRelated] & { log_type: keyof MessageRelated };
export type ChatroomLastMessage = LogMessage<keyof MessageRelated> & BaseInfo & { hidden?: boolean };
